import type {
  VehicleResponse,
  VehicleCreate,
  VehicleUpdate,
  VehicleList,
  VehicleListParams,
  VehicleFuelRecordResponse,
  VehicleFuelRecordCreate,
  VehicleFuelRecordUpdate,
  VehicleFuelRecordList,
  VehicleFuelRecordListParams,
  VehicleFuelRecordWithStats,
  VehicleWithFuelStats,
  FuelConsumptionStats,
  FuelConsumptionStatsParams,
  FuelCostSummaryParams,
} from "@/types/vehicle";

import { API_BASE_URL } from "./api";

// 基础API配置
const apiConfig = {
  baseURL: `${API_BASE_URL}/api/v1`,
  headers: {
    "Content-Type": "application/json",
  },
};

// 获取认证头
function getAuthHeaders(): Record<string, string> {
  const token = localStorage.getItem("access_token");
  return token ? { Authorization: `Bearer ${token}` } : {};
}

// 处理API响应
async function handleResponse<T>(response: Response): Promise<T> {
  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(
      errorData.detail || `HTTP error! status: ${response.status}`,
    );
  }
  return response.json();
}

// 车辆管理API
export const vehicleApi = {
  // 获取车辆列表
  async getVehicles(params?: VehicleListParams): Promise<VehicleList> {
    const searchParams = new URLSearchParams();
    if (params?.skip !== undefined)
      searchParams.append("skip", params.skip.toString());
    if (params?.limit !== undefined)
      searchParams.append("limit", params.limit.toString());
    if (params?.is_active !== null && params?.is_active !== undefined)
      searchParams.append("is_active", params.is_active.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/vehicles?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<VehicleList>(response);
  },

  // 获取单个车辆
  async getVehicle(vehicleId: number): Promise<VehicleResponse> {
    const response = await fetch(`${apiConfig.baseURL}/vehicles/${vehicleId}`, {
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
    });

    return handleResponse<VehicleResponse>(response);
  },

  // 创建车辆
  async createVehicle(vehicle: VehicleCreate): Promise<VehicleResponse> {
    const response = await fetch(`${apiConfig.baseURL}/vehicles`, {
      method: "POST",
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
      body: JSON.stringify(vehicle),
    });

    return handleResponse<VehicleResponse>(response);
  },

  // 更新车辆
  async updateVehicle(
    vehicleId: number,
    vehicle: VehicleUpdate,
  ): Promise<VehicleResponse> {
    const response = await fetch(`${apiConfig.baseURL}/vehicles/${vehicleId}`, {
      method: "PUT",
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
      body: JSON.stringify(vehicle),
    });

    return handleResponse<VehicleResponse>(response);
  },

  // 删除车辆
  async deleteVehicle(vehicleId: number): Promise<void> {
    const response = await fetch(`${apiConfig.baseURL}/vehicles/${vehicleId}`, {
      method: "DELETE",
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
    });

    return handleResponse<void>(response);
  },

  // 获取带油耗统计的车辆列表
  async getVehiclesWithStats(): Promise<VehicleWithFuelStats[]> {
    const response = await fetch(`${apiConfig.baseURL}/vehicles/with-stats`, {
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
    });

    return handleResponse<VehicleWithFuelStats[]>(response);
  },
};

// 加油记录管理API
export const fuelRecordApi = {
  // 获取加油记录列表
  async getFuelRecords(
    params?: VehicleFuelRecordListParams,
  ): Promise<VehicleFuelRecordList> {
    const searchParams = new URLSearchParams();
    if (params?.skip !== undefined)
      searchParams.append("skip", params.skip.toString());
    if (params?.limit !== undefined)
      searchParams.append("limit", params.limit.toString());
    if (params?.start_date)
      searchParams.append("start_date", params.start_date);
    if (params?.end_date) searchParams.append("end_date", params.end_date);
    if (params?.gas_station_type)
      searchParams.append("gas_station_type", params.gas_station_type);
    if (params?.vehicle_id)
      searchParams.append("vehicle_id", params.vehicle_id.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/fuel-records?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<VehicleFuelRecordList>(response);
  },

  // 获取单个加油记录
  async getFuelRecord(recordId: number): Promise<VehicleFuelRecordResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/fuel-records/${recordId}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<VehicleFuelRecordResponse>(response);
  },

  // 创建加油记录
  async createFuelRecord(
    record: VehicleFuelRecordCreate,
  ): Promise<VehicleFuelRecordWithStats> {
    const response = await fetch(`${apiConfig.baseURL}/fuel-records`, {
      method: "POST",
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
      body: JSON.stringify(record),
    });

    return handleResponse<VehicleFuelRecordWithStats>(response);
  },

  // 更新加油记录
  async updateFuelRecord(
    recordId: number,
    record: VehicleFuelRecordUpdate,
  ): Promise<VehicleFuelRecordWithStats> {
    const response = await fetch(
      `${apiConfig.baseURL}/fuel-records/${recordId}`,
      {
        method: "PUT",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
        body: JSON.stringify(record),
      },
    );

    return handleResponse<VehicleFuelRecordWithStats>(response);
  },

  // 删除加油记录
  async deleteFuelRecord(recordId: number): Promise<void> {
    const response = await fetch(
      `${apiConfig.baseURL}/fuel-records/${recordId}`,
      {
        method: "DELETE",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<void>(response);
  },

  // 根据车辆ID获取加油记录
  async getFuelRecordsByVehicle(
    vehicleId: number,
    params?: { skip?: number; limit?: number },
  ): Promise<VehicleFuelRecordList> {
    const searchParams = new URLSearchParams();
    if (params?.skip !== undefined)
      searchParams.append("skip", params.skip.toString());
    if (params?.limit !== undefined)
      searchParams.append("limit", params.limit.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/vehicles/${vehicleId}/fuel-records?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<VehicleFuelRecordList>(response);
  },

  // 获取指定车辆的最新加油记录
  async getLatestFuelRecord(
    vehicleId: number,
  ): Promise<VehicleFuelRecordResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/vehicles/${vehicleId}/fuel-records/latest`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<VehicleFuelRecordResponse>(response);
  },

  // 根据加油站类型获取加油记录
  async getFuelRecordsByStation(
    stationType: string,
    params?: { skip?: number; limit?: number },
  ): Promise<VehicleFuelRecordList> {
    const searchParams = new URLSearchParams();
    if (params?.skip !== undefined)
      searchParams.append("skip", params.skip.toString());
    if (params?.limit !== undefined)
      searchParams.append("limit", params.limit.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/fuel-records/by-station/${stationType}?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<VehicleFuelRecordList>(response);
  },
};

// 油耗统计API
export const fuelStatsApi = {
  // 获取油耗统计信息
  async getFuelConsumptionStats(
    params?: FuelConsumptionStatsParams,
  ): Promise<FuelConsumptionStats | null> {
    const searchParams = new URLSearchParams();
    if (params?.start_date)
      searchParams.append("start_date", params.start_date);
    if (params?.end_date) searchParams.append("end_date", params.end_date);
    if (params?.vehicle_id)
      searchParams.append("vehicle_id", params.vehicle_id.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/fuel-stats/consumption?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<FuelConsumptionStats | null>(response);
  },

  // 获取加油费用汇总
  async getFuelCostSummary(params?: FuelCostSummaryParams): Promise<{
    total_cost?: number;
    monthly_average?: number;
    daily_average?: number;
  }> {
    const searchParams = new URLSearchParams();
    if (params?.start_date)
      searchParams.append("start_date", params.start_date);
    if (params?.end_date) searchParams.append("end_date", params.end_date);
    if (params?.vehicle_id)
      searchParams.append("vehicle_id", params.vehicle_id.toString());

    const response = await fetch(
      `${apiConfig.baseURL}/fuel-stats/cost-summary?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<{
      total_cost?: number;
      monthly_average?: number;
      daily_average?: number;
    }>(response);
  },

  // 获取支持的加油站类型列表
  async getGasStationTypes(): Promise<string[]> {
    const response = await fetch(`${apiConfig.baseURL}/fuel-stations/types`, {
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
    });

    return handleResponse<string[]>(response);
  },
};
